/**
 * 工具类
 */
export interface IDataFormat {
  formatDate: Function
}

const DataFormat: IDataFormat = {
  /**
   * 格式化时间
   * @param date 时间
   * @param format 格式化之后的时间格式（）
   */
  formatDate(date: Date, format: string): String {

    const DATETIME_FORMAT = 'yyyy-MM-dd hh:mm:ss'

    if (format === undefined) {
      format = DATETIME_FORMAT
    }

    /**
     * 补零
     * @param vNumber 需要补零的数
     * @param width 补零的个数
     */
    function padWithZeros(vNumber: number, width: number): string {
      let numAsString = vNumber.toString()
      while (numAsString.length < width) {
        numAsString = '0' + numAsString
      }
      return numAsString
    }

    /**
     * 补零
     * @param vNumber 需要补零的数
     */
    function addZero(vNumber: number): string {
      return padWithZeros(vNumber, 2)
    }

    /**
     * 计算时差，以分钟为单位
     * @param timezoneOffset 时间偏移量
     */
    function offset(timezoneOffset: number): string {
      const os = Math.abs(timezoneOffset)
      let h = String(Math.floor(os / 60))
      let m = String(os % 60)
      if (h.length === 1) {
        h = '0' + h
      }
      if (m.length === 1) {
        m = '0' + m
      }
      return timezoneOffset < 0 ? '+' + h + m : '-' + h + m
    }

    const vDay: string = addZero(date.getDate())
    const vMonth: string = addZero((date.getMonth()) + 1)
    const vYearLong: string = addZero(date.getFullYear())
    const vYearShort: string = addZero(Number(vYearLong.substring(2, 4)))
    const vYear: string = format.indexOf('yyyy') > -1 ? vYearLong : vYearShort
    const vHour: string = addZero(date.getHours())
    const vMinute: string = addZero(date.getMinutes())
    const vSecond: string = addZero(date.getSeconds())
    const vMillisecond: string = padWithZeros(date.getMilliseconds(), 3)
    const vTimeZone: string = offset(date.getTimezoneOffset())
    const formatted: string = format
      .replace(/dd/g, vDay)
      .replace(/MM/g, vMonth)
      .replace(/y{1,4}/g, vYear)
      .replace(/hh/g, vHour)
      .replace(/mm/g, vMinute)
      .replace(/ss/g, vSecond)
      .replace(/SSS/g, vMillisecond)
      .replace(/O/g, vTimeZone)
    return formatted
  }

}

export default DataFormat